Popular Searches
Popular Course Categories
Popular Courses

WebDriver with Python

WebDriver with Python

Selenium with Python

WebDriver with Python

WebDriver with Python is a powerful approach for automating web browsers and testing web applications using Python programming language and Selenium WebDriver. Selenium WebDriver allows Python programs to control browsers such as Chrome, Firefox, Edge, and Safari, perform user-like actions, locate web elements, validate application behavior, and execute automated test cases.

Python provides a simple and readable programming syntax, while Selenium WebDriver provides browser automation capabilities. Together, they are widely used for web application testing, regression testing, functional testing, smoke testing, end-to-end testing, and automation framework development.

For structured Selenium learning, explore Selenium Training and Register for Course Demo.


1. What is Selenium WebDriver?

Selenium WebDriver is a browser automation technology that allows programs to communicate directly with web browsers and perform actions similar to a real user.

Using WebDriver with Python, a tester can open a browser, navigate to a website, find elements, enter text, click buttons, select options, handle alerts, switch between frames and windows, capture screenshots, and verify expected results.

WebDriver is one of the major components of the Selenium project and is primarily used for automating web applications.

Example

from selenium import webdriver

 

driver = webdriver.Chrome()

driver.get("https://example.com")

print(driver.title)

driver.quit()


2. What is Python?

Python is a high-level, interpreted programming language known for its readable syntax and extensive library ecosystem. In Selenium automation, Python is used to write test scripts that communicate with browsers through Selenium WebDriver.

Important Python concepts used in Selenium automation include:

  • Variables
  • Data types
  • Operators
  • Conditional statements
  • Loops
  • Functions
  • Lists, tuples, sets, and dictionaries
  • Classes and objects
  • Inheritance
  • Exception handling
  • File handling
  • Modules and packages


3. Why Use Python with Selenium?

Python makes Selenium automation easier to learn and maintain because of its simple syntax and large ecosystem.

FeatureBenefit
Simple SyntaxAutomation scripts are easy to read and understand.
Fast DevelopmentTest scripts can be created quickly.
Large EcosystemPython provides many testing and automation libraries.
pytest SupportAutomation tests can be organized and executed using pytest.
Cross-PlatformPython automation can run on Windows, macOS, and Linux.
Reusable CodeFunctions, classes, modules, and Page Object Model can be used.
Easy DebuggingReadable code makes debugging easier.


4. Selenium Architecture with Python

The basic relationship between Python, Selenium, WebDriver, and the browser can be represented as:

Python Test Script

       |

       v

Selenium Python Library

       |

       v

WebDriver

       |

       v

Browser Driver / Selenium Manager

       |

       v

Chrome / Firefox / Edge / Safari

       |

       v

Web Application

The Python test script sends commands through the Selenium Python package. WebDriver communicates with the browser and performs the requested operations.


5. Selenium Components

The Selenium project consists of multiple tools and technologies.

ComponentDescription
Selenium WebDriverAutomates browsers programmatically.
Selenium IDEProvides browser-based record-and-playback capabilities.
Selenium GridSupports remote and distributed test execution.

For Python automation, Selenium WebDriver is the primary component used.


6. Installing Python

Before using Selenium with Python, Python should be installed on the system.

After installation, verify the Python version from the terminal or command prompt.

python --version

On some systems, the following command may be required:

python3 --version

Example Output

Python 3.x.x


7. Checking pip

pip is Python's package installer. It is used to install Selenium and other Python packages.

pip --version

If the system uses pip3, use:

pip3 --version


8. Installing Selenium

Selenium can be installed using pip.

pip install selenium

For systems where Python 3 is explicitly invoked:

pip3 install selenium

After installation, Selenium can be imported into a Python program.

from selenium import webdriver


9. Using a Virtual Environment

A virtual environment creates an isolated Python environment for a project. It prevents project dependencies from interfering with packages installed for other projects.

Create Virtual Environment

python -m venv venv

Activate on Windows

venv\Scripts\activate

Activate on macOS/Linux

source venv/bin/activate

Install Selenium

pip install selenium


10. Importing Selenium WebDriver

The Selenium WebDriver module can be imported using:

from selenium import webdriver

The webdriver module provides browser-specific WebDriver classes such as Chrome, Firefox, Edge, and Safari.


11. Creating a Chrome WebDriver

Chrome automation can be started using webdriver.Chrome().

from selenium import webdriver

 

driver = webdriver.Chrome()

driver.get("https://example.com")

 

print(driver.title)

 

driver.quit()

Modern Selenium versions include Selenium Manager, which can assist with browser driver management in supported environments.


12. Creating an Edge WebDriver

from selenium import webdriver

 

driver = webdriver.Edge()

driver.get("https://example.com")

 

print(driver.title)

 

driver.quit()


13. Creating a Firefox WebDriver

from selenium import webdriver

 

driver = webdriver.Firefox()

driver.get("https://example.com")

 

print(driver.title)

 

driver.quit()


14. Creating a Safari WebDriver

Safari WebDriver is primarily used on macOS systems.

from selenium import webdriver

 

driver = webdriver.Safari()

driver.get("https://example.com")

 

print(driver.title)

 

driver.quit()


15. First WebDriver with Python Program

The following program opens Chrome, navigates to a website, displays the page title, and closes the browser.

from selenium import webdriver

 

driver = webdriver.Chrome()

 

driver.get("https://example.com")

 

print("Page Title:", driver.title)

 

driver.quit()

Execution Flow

Start

  |

  v

Create WebDriver

  |

  v

Open Browser

  |

  v

Open Website

  |

  v

Read Page Title

  |

  v

Close Browser

  |

  v

End


16. WebDriver Object

The WebDriver object represents the browser session controlled by the Python program.

driver = webdriver.Chrome()

Once the object is created, various browser operations can be performed.

driver.get("https://example.com")

driver.refresh()

driver.back()

driver.forward()

driver.quit()


17. Opening a Website with get()

The get() method navigates the browser to a specified URL.

driver.get("https://example.com")

Example:

from selenium import webdriver

 

driver = webdriver.Chrome()

driver.get("https://www.google.com")

 

driver.quit()


18. Finding Web Elements

Web applications contain elements such as text boxes, buttons, links, checkboxes, dropdowns, images, and forms. Selenium uses locators to identify these elements.

Common Selenium locators include:

  • ID
  • NAME
  • CLASS_NAME
  • TAG_NAME
  • LINK_TEXT
  • PARTIAL_LINK_TEXT
  • CSS_SELECTOR
  • XPATH


19. Using the By Class

The By class provides standard locator strategies for finding web elements.

from selenium.webdriver.common.by import By

Common Locator Strategies

LocatorPython Syntax
IDBy.ID
NameBy.NAME
Class NameBy.CLASS_NAME
Tag NameBy.TAG_NAME
Link TextBy.LINK_TEXT
Partial Link TextBy.PARTIAL_LINK_TEXT
CSS SelectorBy.CSS_SELECTOR
XPathBy.XPATH


20. Finding an Element by ID

ID is generally a convenient locator when an element has a unique and stable ID.

from selenium.webdriver.common.by import By

 

username = driver.find_element(By.ID, "username")

username.send_keys("admin")


21. Finding an Element by Name

email = driver.find_element(By.NAME, "email")

email.send_keys("[email protected]")


22. Finding an Element by Class Name

button = driver.find_element(By.CLASS_NAME, "login-button")

button.click()


23. Finding an Element by Tag Name

links = driver.find_elements(By.TAG_NAME, "a")

 

for link in links:

    print(link.text)


24. Finding an Element by Link Text

login_link = driver.find_element(By.LINK_TEXT, "Login")

login_link.click()


25. Finding an Element by Partial Link Text

link = driver.find_element(By.PARTIAL_LINK_TEXT, "Log")

link.click()


26. Finding an Element with CSS Selector

CSS selectors provide a flexible way to locate elements using HTML attributes, classes, IDs, hierarchy, and other selector patterns.

search_box = driver.find_element(By.CSS_SELECTOR, "#search")

search_box.send_keys("Selenium")

Example

button = driver.find_element(By.CSS_SELECTOR, "button.login")

button.click()


27. Finding an Element with XPath

XPath can locate elements based on their structure, attributes, text, and relationships with other elements.

username = driver.find_element(By.XPATH, "//input[@id='username']")

username.send_keys("admin")

Text-Based XPath

button = driver.find_element(By.XPATH, "//button[text()='Login']")

button.click()


28. find_element() Method

find_element() returns a single matching web element. If Selenium cannot find the element, an exception can be raised.

element = driver.find_element(By.ID, "username")

element.click()


29. find_elements() Method

find_elements() returns a collection of matching elements.

links = driver.find_elements(By.TAG_NAME, "a")

 

for link in links:

    print(link.text)

Difference

MethodResult
find_element()Returns one matching element.
find_elements()Returns a collection of matching elements.


30. Working with WebElement

A WebElement represents an HTML element located by Selenium.

Common WebElement operations include:

  • click()
  • send_keys()
  • clear()
  • get_attribute()
  • is_displayed()
  • is_enabled()
  • is_selected()
  • text


31. send_keys()

The send_keys() method enters keyboard input into an element.

username = driver.find_element(By.ID, "username")

username.send_keys("admin")


32. click()

The click() method performs a click action on an element.

login_button = driver.find_element(By.ID, "login")

login_button.click()


33. clear()

The clear() method removes existing text from an editable field.

search_box = driver.find_element(By.ID, "search")

search_box.clear()

search_box.send_keys("Selenium")


34. Reading Text from an Element

message = driver.find_element(By.ID, "message")

 

print(message.text)


35. Checking Element State

element = driver.find_element(By.ID, "submit")

 

print(element.is_displayed())

print(element.is_enabled())

print(element.is_selected())


36. Browser Navigation

Selenium WebDriver provides browser navigation methods.

driver.get("https://example.com")

 

driver.back()

driver.forward()

driver.refresh()

MethodPurpose
get()Open a URL.
back()Move to the previous page.
forward()Move to the next page.
refresh()Reload the current page.


37. Browser Information

WebDriver provides properties that allow the test to retrieve information about the current browser session.

print(driver.title)

print(driver.current_url)

print(driver.current_window_handle)


38. Browser Window Size

The browser window can be controlled using WebDriver window methods.

driver.maximize_window()

driver.minimize_window()

A fixed browser size can also be configured when required by a test environment.


39. close() vs quit()

MethodPurpose
close()Closes the current browser window or tab.
quit()Ends the WebDriver session and closes associated browser windows.

For complete test cleanup, driver.quit() is generally preferred.


40. Using try-finally with WebDriver

A finally block can be used to ensure the browser session is closed even if an exception occurs.

from selenium import webdriver

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com")

    print(driver.title)

finally:

    driver.quit()


41. Selenium Exceptions

Selenium provides exceptions that help identify problems during browser automation.

Common exceptions include:

  • NoSuchElementException
  • TimeoutException
  • ElementNotInteractableException
  • ElementClickInterceptedException
  • StaleElementReferenceException
  • InvalidSelectorException
  • WebDriverException


42. Exception Handling

Python's try-except statement can be used to handle Selenium exceptions.

from selenium import webdriver

from selenium.common.exceptions import NoSuchElementException

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com")

    element = driver.find_element(By.ID, "missing")

except NoSuchElementException:

    print("Element was not found.")

finally:

    driver.quit()


43. Explicit Waits with WebDriverWait

Modern web applications often load elements dynamically. An explicit wait allows Selenium to wait for a specific condition instead of immediately trying to interact with an element.

from selenium.webdriver.support.ui import WebDriverWait

 

wait = WebDriverWait(driver, 10)


44. Expected Conditions

Expected Conditions provide commonly used conditions for explicit waits.

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

wait = WebDriverWait(driver, 10)

 

login_button = wait.until(

    EC.element_to_be_clickable((By.ID, "login"))

)

 

login_button.click()

Common Expected Conditions

  • presence_of_element_located
  • visibility_of_element_located
  • element_to_be_clickable
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • alert_is_present
  • frame_to_be_available_and_switch_to_it


45. Implicit Wait

An implicit wait instructs WebDriver to wait for a specified amount of time when searching for elements.

driver.implicitly_wait(10)

Implicit waits should be used thoughtfully because they apply globally to element searches.


46. Explicit Wait vs Implicit Wait

Implicit WaitExplicit Wait
Applies globally to element searches.Targets a specific condition.
Simple to configure.More precise.
Less flexible.Highly flexible.
Useful for general synchronization.Useful for dynamic application behavior.


47. Handling Mouse and Keyboard Actions

The ActionChains class is used for advanced mouse and keyboard interactions.

from selenium.webdriver.common.action_chains import ActionChains

 

actions = ActionChains(driver)


48. Mouse Hover

menu = driver.find_element(By.ID, "menu")

 

ActionChains(driver).move_to_element(menu).perform()


49. Double Click

element = driver.find_element(By.ID, "item")

 

ActionChains(driver).double_click(element).perform()


50. Right Click

element = driver.find_element(By.ID, "item")

 

ActionChains(driver).context_click(element).perform()


51. Drag and Drop

source = driver.find_element(By.ID, "source")

target = driver.find_element(By.ID, "target")

 

ActionChains(driver).drag_and_drop(source, target).perform()


52. Handling Dropdowns

The Selenium Select class can be used for standard HTML select elements.

from selenium.webdriver.support.ui import Select

 

dropdown = driver.find_element(By.ID, "country")

select = Select(dropdown)

Select by Visible Text

select.select_by_visible_text("India")

Select by Value

select.select_by_value("IN")

Select by Index

select.select_by_index(1)


53. Handling JavaScript Alerts

Selenium can switch to browser alerts using the alert object.

alert = driver.switch_to.alert

 

print(alert.text)

alert.accept()

Dismiss Alert

alert.dismiss()

Enter Text in Prompt

alert.send_keys("Test")

alert.accept()


54. Handling Frames and iFrames

When an element is located inside an iframe, Selenium must switch to that frame before interacting with the element.

driver.switch_to.frame("frame_name")

 

element = driver.find_element(By.ID, "username")

element.send_keys("admin")

 

driver.switch_to.default_content()


55. Handling Multiple Windows and Tabs

Selenium provides window handles for identifying browser windows and tabs.

original_window = driver.current_window_handle

 

print(driver.window_handles)

After a new window or tab is opened, Selenium can switch to it.

for window in driver.window_handles:

    if window != original_window:

        driver.switch_to.window(window)

        break


56. Taking Screenshots

Screenshots are useful for debugging failed automation tests and maintaining test evidence.

driver.save_screenshot("homepage.png")

Screenshot functionality can also be added to exception handling and test reporting workflows.


57. Handling Cookies

Selenium can read, add, and delete browser cookies.

Get Cookies

cookies = driver.get_cookies()

 

for cookie in cookies:

    print(cookie)

Add Cookie

driver.add_cookie({

    "name": "test_cookie",

    "value": "12345"

})

Delete Cookie

driver.delete_cookie("test_cookie")

Delete All Cookies

driver.delete_all_cookies()


58. Executing JavaScript

Selenium allows JavaScript code to be executed inside the current browser context.

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Reading Page Information

title = driver.execute_script("return document.title;")

print(title)

JavaScript execution should generally be used when normal WebDriver interactions are insufficient or when a specific browser-side operation is required.


59. Browser Options

Browser options allow automation behavior to be configured before creating the WebDriver instance.

Chrome Options Example

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

 

options = Options()

options.add_argument("--start-maximized")

 

driver = webdriver.Chrome(options=options)

 

driver.get("https://example.com")

driver.quit()

Headless Browser

options = Options()

options.add_argument("--headless")

 

driver = webdriver.Chrome(options=options)


60. Remote WebDriver

Remote WebDriver allows tests to communicate with a WebDriver server or remote browser infrastructure.

from selenium import webdriver

 

driver = webdriver.Remote(

    command_executor="http://localhost:4444",

    options=options

)

 

driver.get("https://example.com")

driver.quit()

Remote execution is useful for Selenium Grid and distributed test environments.


61. Selenium with pytest

pytest is a popular Python testing framework that can be used to organize and execute Selenium tests.

import pytest

from selenium import webdriver

 

def test_homepage():

    driver = webdriver.Chrome()

 

    try:

        driver.get("https://example.com")

        assert "Example" in driver.title

    finally:

        driver.quit()

Install pytest

pip install pytest

Run Tests

pytest


62. Selenium with unittest

Python's built-in unittest framework can also be used to organize Selenium tests.

import unittest

from selenium import webdriver

 

class LoginTest(unittest.TestCase):

 

    def setUp(self):

        self.driver = webdriver.Chrome()

 

    def test_homepage(self):

        self.driver.get("https://example.com")

        self.assertIn("Example", self.driver.title)

 

    def tearDown(self):

        self.driver.quit()

 

if __name__ == "__main__":

    unittest.main()


63. Page Object Model with Python

Page Object Model (POM) is a design pattern commonly used to organize Selenium automation code. Each web page or major page component can be represented by a Python class.

Example Page Class

from selenium.webdriver.common.by import By

 

class LoginPage:

 

    def __init__(self, driver):

        self.driver = driver

        self.username = (By.ID, "username")

        self.password = (By.ID, "password")

        self.login_button = (By.ID, "login")

 

    def login(self, username, password):

        self.driver.find_element(*self.username).send_keys(username)

        self.driver.find_element(*self.password).send_keys(password)

        self.driver.find_element(*self.login_button).click()

POM separates page-specific element locators and actions from test logic, improving maintainability and reuse.


64. Data-Driven Selenium Testing

Data-driven testing executes the same test scenario with multiple sets of test data.

test_data = [

    ("user1", "Test@123"),

    ("user2", "Test@456"),

    ("user3", "Test@789")

]

 

for username, password in test_data:

    print(username, password)

Test data can also be stored in CSV, JSON, Excel, databases, or other external sources.


65. Selenium Project Requirements File

A requirements.txt file can be used to record Python project dependencies.

selenium

pytest

Install project dependencies using:

pip install -r requirements.txt


66. Checking Installed Selenium Package

The installed Selenium package can be checked using pip.

pip show selenium

Another option is:

pip list


67. Checking Selenium Version

The Selenium version can be checked directly from Python.

import selenium

 

print(selenium.__version__)


68. Selenium Manager

Modern Selenium versions include Selenium Manager to assist with browser driver management. This reduces the need for manually downloading and configuring browser drivers in many standard setups.

The basic WebDriver creation can therefore remain simple:

from selenium import webdriver

 

driver = webdriver.Chrome()

driver.get("https://example.com")

driver.quit()


69. Common WebDriver Errors

ErrorPossible CausePossible Solution
NoSuchElementExceptionElement cannot be located.Check locator and page state.
TimeoutExceptionExpected condition was not met.Review wait condition and timeout.
ElementNotInteractableExceptionElement cannot currently be interacted with.Wait for visibility or usability.
ElementClickInterceptedExceptionAnother element blocks the click.Wait for overlays or use an appropriate interaction strategy.
StaleElementReferenceExceptionElement reference is no longer valid.Locate the element again.
InvalidSelectorExceptionLocator syntax is invalid.Correct the CSS or XPath selector.
WebDriverExceptionGeneral WebDriver-related problem.Check browser, driver, configuration, and environment.


70. Complete WebDriver with Python Example

The following example demonstrates a basic end-to-end Selenium workflow.

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com")

 

    print("Title:", driver.title)

    print("URL:", driver.current_url)

 

    wait = WebDriverWait(driver, 10)

 

    element = wait.until(

        EC.presence_of_element_located((By.TAG_NAME, "body"))

    )

 

    print("Page text:")

    print(element.text)

 

finally:

    driver.quit()


71. Recommended Selenium Python Project Structure

selenium_project/

|

+-- tests/

|   +-- test_login.py

|   +-- test_search.py

|

+-- pages/

|   +-- login_page.py

|   +-- home_page.py

|

+-- utilities/

|   +-- config.py

|   +-- test_data.py

|

+-- screenshots/

|

+-- reports/

|

+-- requirements.txt

|

+-- pytest.ini

|

+-- README.md

This type of structure helps separate tests, page objects, reusable utilities, test data, screenshots, and reports.


72. Best Practices for WebDriver with Python

  • Use a virtual environment for each automation project.
  • Use meaningful test and variable names.
  • Prefer stable locators.
  • Avoid unnecessary hard-coded sleep statements.
  • Use explicit waits for dynamic elements.
  • Keep page locators inside Page Object classes when using POM.
  • Use reusable functions for common operations.
  • Capture screenshots when useful for failure analysis.
  • Use driver.quit() for complete browser cleanup.
  • Keep test data separate from test logic.
  • Use requirements.txt to manage project dependencies.
  • Use version control such as Git for automation projects.
  • Keep test cases independent where practical.
  • Use logging and reporting for larger automation projects.
  • Avoid excessive use of JavaScript when normal WebDriver operations are sufficient.


73. Common Mistakes in Selenium Python

  • Using incorrect locators.
  • Using absolute XPath unnecessarily.
  • Using fixed delays everywhere.
  • Not waiting for dynamically loaded elements.
  • Forgetting to close the browser.
  • Mixing test logic and page locator logic in large projects.
  • Hard-coding credentials in source code.
  • Ignoring exceptions during test execution.
  • Creating duplicate automation code.
  • Not maintaining dependencies.
  • Using unstable elements or dynamically generated attributes as locators without considering stability.


74. WebDriver with Python Learning Flow

Python Fundamentals

        |

        v

Selenium Installation

        |

        v

WebDriver Basics

        |

        v

Browser Automation

        |

        v

Locators

        |

        v

WebElement Operations

        |

        v

Waits and Synchronization

        |

        v

Alerts / Frames / Windows

        |

        v

Mouse and Keyboard Actions

        |

        v

pytest / unittest

        |

        v

Page Object Model

        |

        v

Data-Driven Testing

        |

        v

Reporting and Debugging

        |

        v

Automation Framework

        |

        v

CI/CD and Advanced Automation


75. WebDriver with Python vs Manual Testing

WebDriver AutomationManual Testing
Tests are executed through automation scripts.Tester manually performs test steps.
Useful for repetitive scenarios.Useful for exploratory and human-centered testing.
Tests can be repeated consistently.Execution depends on manual effort.
Requires programming and automation maintenance.Requires test execution and domain knowledge.
Can be integrated into automated pipelines.Manual execution is generally not directly automated.


76. WebDriver with Python vs Selenium with Java

PythonJava
Concise syntax.More verbose syntax.
Easy to learn for beginners.Strong enterprise ecosystem.
Works with pytest and unittest.Commonly works with TestNG and JUnit.
Fast script development.Strong object-oriented programming ecosystem.
Large automation and scripting ecosystem.Widely used in enterprise automation environments.


77. Real-World Applications of WebDriver with Python

  • Login and authentication testing
  • Registration form testing
  • E-commerce testing
  • Shopping cart automation
  • Search functionality testing
  • Banking application testing
  • Booking application testing
  • CRM application testing
  • Regression test automation
  • Smoke test automation
  • Cross-browser testing
  • End-to-end testing
  • Data-driven testing
  • Continuous integration testing


78. Practical Exercise

Create a Selenium Python program that performs the following steps:

  1. Open Chrome.
  2. Navigate to a test website.
  3. Read the page title.
  4. Find a text field.
  5. Enter test data.
  6. Find and click a button.
  7. Wait for a result.
  8. Print the result.
  9. Capture a screenshot.
  10. Close the browser.

Expected Automation Flow

Launch Browser

      |

      v

Open Website

      |

      v

Locate Element

      |

      v

Enter Data

      |

      v

Click Button

      |

      v

Wait for Result

      |

      v

Validate Result

      |

      v

Take Screenshot

      |

      v

Quit Browser


79. Practical Project: Selenium Python Login Automation

A beginner-friendly Selenium project is an automated login test. The project can validate that a user can enter credentials, submit the login form, and reach the expected page.

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

 

driver = webdriver.Chrome()

 

try:

    driver.get("https://example.com/login")

 

    username = driver.find_element(By.ID, "username")

    password = driver.find_element(By.ID, "password")

 

    username.send_keys("testuser")

    password.send_keys("Test@123")

 

    login_button = WebDriverWait(driver, 10).until(

        EC.element_to_be_clickable((By.ID, "login"))

    )

 

    login_button.click()

 

    print("Login test executed successfully.")

 

finally:

    driver.quit()

Project Enhancements

  • Add positive and negative login scenarios.
  • Use Page Object Model.
  • Move credentials to test data or secure configuration.
  • Add explicit waits.
  • Add screenshots on failure.
  • Generate test reports.
  • Execute tests using pytest.
  • Run tests on multiple browsers.
  • Integrate the project with Git.
  • Execute the tests through a CI/CD pipeline.


80. Interview Questions on WebDriver with Python

Q1. What is Selenium WebDriver?

Selenium WebDriver is a browser automation technology that allows programs to control web browsers and automate web application interactions.

Q2. Why is Python used with Selenium?

Python provides simple syntax, rapid development, strong testing libraries, and an extensive ecosystem for automation.

Q3. How do you create a Chrome WebDriver?

from selenium import webdriver

 

driver = webdriver.Chrome()

Q4. How do you open a website?

driver.get("https://example.com")

Q5. What is the difference between find_element() and find_elements()?

find_element() returns one matching element, while find_elements() returns a collection of matching elements.

Q6. What is the By class?

The By class provides locator strategies such as ID, NAME, CSS_SELECTOR, XPATH, and CLASS_NAME.

Q7. What is an explicit wait?

An explicit wait waits for a specific condition before continuing the test.

Q8. What is Page Object Model?

Page Object Model is a design pattern that separates page-specific elements and actions from test logic.

Q9. What is the difference between close() and quit()?

close() closes the current browser window or tab, while quit() terminates the WebDriver session and closes associated browser windows.

Q10. How can you take a screenshot?

driver.save_screenshot("screenshot.png")


81. Quick Revision Table

ConceptSyntax / Example
Import WebDriverfrom selenium import webdriver
Create Chromewebdriver.Chrome()
Open URLdriver.get(url)
Find Elementdriver.find_element()
Find Multiple Elementsdriver.find_elements()
LocatorBy.ID / By.NAME / By.XPATH / By.CSS_SELECTOR
Enter Textelement.send_keys()
Clickelement.click()
Clearelement.clear()
Backdriver.back()
Forwarddriver.forward()
Refreshdriver.refresh()
WaitWebDriverWait()
Mouse ActionActionChains()
DropdownSelect()
Alertdriver.switch_to.alert
Framedriver.switch_to.frame()
Screenshotdriver.save_screenshot()
Cookiesdriver.get_cookies()
JavaScriptdriver.execute_script()
Close Sessiondriver.quit()


82. Final Summary

WebDriver with Python combines Python programming with Selenium's browser automation capabilities. It allows testers and developers to automate web applications, locate and interact with web elements, navigate between pages, handle dynamic content, work with alerts, frames and windows, perform mouse and keyboard operations, take screenshots, manage cookies, and execute JavaScript when necessary.

A strong Selenium Python automation skill set includes Python fundamentals, WebDriver, locators, WebElement methods, waits, exception handling, browser interactions, pytest or unittest, Page Object Model, data-driven testing, project structure, reporting, debugging, Git, and CI/CD concepts.

For practical learning and structured Selenium training, visit JustAcademy Selenium Training and use the Selenium Course Demo Registration page.


83. Course Resources

whatsapp